package top.lyjwn.todo.weinxin.api.bjnews;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.lyjwn.todo.weinxin.api.url.WXBjnewsUrl;
import top.lyjwn.todo.weinxin.bjnews.utils.Scope;
import top.lyjwn.todo.common.utils.http.HttpUtil;

/**
 * 在确保微信公众账号拥有授权作用域（scope参数）的权限的前提下（服务号获得高级接口后，默认拥有scope参数中的snsapi_base和snsapi_userinfo），引导关注者打开如下页面：
 * <p>
 * 此接口只有geturl才能使用，原因是该接口会直接重定向到用户的授权页面，然后再重新向回来(redirectUri是返回时的url)
 *
 * @author luoyujie
 */
@Component
public class GetUserCode {

    @Autowired
    private WXBjnewsUrl wxBjnewsUrl;


    public GetUserCode() {
    }

    public String getUrl(String redirectUri, String scope, String state) {
        String url = wxBjnewsUrl.getUSER_CODE().replace("#{REDIRECT_URI}", redirectUri).replace("#{SCOPE}", scope)
                .replace("#{STATE}", state == null ? "" : state);
        return url;
    }

    public String getUrl(String redirectUri, String scope) {
        String url = this.getUrl(redirectUri, scope, null);
        return url;
    }

    public String getUrl(String redirectUri) {
        String url = this.getUrl(redirectUri, Scope.SNSAPI_BASE);
        return url;
    }

    /**
     * 获取用户接口为重定向接口，以下直接访问接口的方法无效，直接调用会发生未知的异常
     */
    public String getResultString(String redirectUri, String scope, String state) {
        String result = HttpUtil.request(getUrl(redirectUri, scope, state), HttpUtil.METHOD_GET);
        return result;
    }

    public JSONObject getResultJSONObject(String redirectUri, String scope, String state) {
        String result = HttpUtil.request(getUrl(redirectUri, scope, state), HttpUtil.METHOD_GET);
        return JSONObject.parseObject(result);
    }

    public String getResultString(String redirectUri, String scope) {
        String result = HttpUtil.request(getUrl(redirectUri, scope), HttpUtil.METHOD_GET);
        return result;
    }

    public JSONObject getResultJSONObject(String redirectUri, String scope) {
        String result = HttpUtil.request(getUrl(redirectUri, scope), HttpUtil.METHOD_GET);
        return JSONObject.parseObject(result);
    }

    public String getResultString(String redirectUri) {
        String result = HttpUtil.request(getUrl(redirectUri), HttpUtil.METHOD_GET);
        return result;
    }

    public JSONObject getResultJSONObject(String redirectUri) {
        String result = HttpUtil.request(getUrl(redirectUri), HttpUtil.METHOD_GET);
        return JSONObject.parseObject(result);
    }

}
